#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

struct stu
{
	char name[20];
	int age;
};


void print(int arr[],size_t num)
{
	int i = 0;
	for (i = 0; i < num; i++)
	{
		printf("%d ", arr[i]);
	}
}

void print_stu(struct stu* p, size_t sz)
{
	int i = 0;
	for (i = 0; i < sz; i++)
	{
		printf("%s ", (p + i)->name);
		printf("%d\n", (p+i)->age);
	}
}

//int comp_int(const void* e1, const void* e2)
//{
//	return *(int*)e1 - *(int*)e2;
//}
//
//int comp_stu_by_name(const void* e1, const void* e2)
//{
//	return strcmp(((struct stu*)e1)->name, ((struct stu*)e2)->name);
//}
//
//int comp_stu_by_age(void* e1, void* e2)
//{
//	return ((struct stu*)e1)->age - ((struct stu*)e2)->age;
//}

//void test1()
//{
//	int arr[6] = { 8,5,6,7,2,5 };
//	size_t sz = sizeof(arr) / sizeof(arr[0]);
//	qsort(arr, sz, sizeof(arr[0]), comp_int);
//	print(arr, sz);
//}
//
//void test2()
//{
//	struct stu s[3] = { {"zhangshan",18},{"daliu",15},{"lisi",17} };
//	size_t sz = sizeof(s) / sizeof(s[0]);
//	//qsort(s, sz, sizeof(s[0]), comp_stu_by_name);
//	qsort(s, sz, sizeof(s[0]), comp_stu_by_age);
//	print_stu(s, sz);
//}

int comp(void* e1, void* e2)
{
	return *(int*)e1 - *(int*)e2;
}

int comp_age(void* e1, void* e2)
{
	return ((struct stu*)e1)->age - ((struct stu*)e2)->age;
}
int comp_name(void* e1, void* e2)
{
	return strcmp(((struct stu*)e1)->name, ((struct stu*)e2)->name);
}

void swap(char* byt1, char* byt2, size_t width)
{
	int i = 0;
	for (i = 0; i < width; i++)
	{
		char temp = *(byt2 + i);
		*(byt2 + i) = *(byt1 + i);
		*(byt1 + i) = temp;
	}
}

void bubble_sort(void* base, size_t num, size_t width, int (*comp)(const void* e1, const void* e2))
{
	int i = 0;
	for (i = 0; i < num - 1; i++)
	{
		int k = 0;
		for (k = 0; k < num - 1 - i; k++)
		{
			if (comp((char*)base + width * k, (char*)base + width * (k + 1)) > 0)
			{
				swap((char*)base + width * k, (char*)base + width * (k + 1), width);
			}
		}
	}
}

//int test3()
//{
//	int arr[] = { 5,7,8,1,23,4,5,1 };
//	int sz = sizeof(arr) / sizeof(arr[0]);
//	bubble_sort(arr, sz, sizeof(arr[0]), comp);
//	print(arr,sz);
//}

int test4()
{
	struct stu s1 = { "fanzhendong",4 };
	struct stu s2 = { "malong",2 };
	struct stu s3 = { "zhangjike",1 };
	struct stu s4 = { "xuxin",3 };
	struct stu s[4] = { s1,s2,s3,s4 };
	size_t sz = sizeof(s) / sizeof(s[0]);
	//bubble_sort(s, sz, sizeof(s[0]), comp_age);
	bubble_sort(s, sz, sizeof(s[0]), comp_name);
	print_stu(s, sz);
}

int main()
{
	//test1();
	//test2();
	//test3();
	test4();

	return 0;
}